#include "file_system.h"
#include "disk.h"
#include "head.h"
#include<stdlib.h>
#include<string.h>

int file_system_read_block(unsigned int block_num, char *buf){
    return !(!disk_read_block(block_num*2, buf) && !disk_read_block(block_num*2 + 1, buf + DEVICE_BLOCK_SIZE));
}

int file_system_write_block(unsigned int block_num, char *buf){
    return !(!disk_write_block(block_num*2, buf) && !disk_write_block(block_num*2 + 1, buf + DEVICE_BLOCK_SIZE));
}

int file_system_read_super(char *buf){
    return file_system_read_block(0, buf);
}

int file_system_write_super(char *buf){
    return file_system_write_block(0, buf);
}

struct inode* file_system_read_inode(unsigned int inode_id, char *buf){
    if(inode_id < 0 || inode_id >= 1024){
        return NULL;
    }
    file_system_read_block(1 + inode_id/32, buf);
    struct inode *p = malloc(sizeof(struct inode));
    memcpy(p, buf + inode_id%32 * sizeof(struct inode), sizeof(struct inode));
    return p;
}

void file_system_write_inode(unsigned int inode_id, struct inode* p, char *buf){
    if(inode_id < 0 || inode_id >= 1024){
        return NULL;
    }
    struct inode tmp = *p;
    file_system_read_block(1 + inode_id/32, buf);
    memcpy(buf + inode_id%32 * sizeof(struct inode), (char*)&tmp, sizeof(struct inode));
    file_system_write_block(1 + inode_id/32, buf);
}

int file_system_read_data(unsigned int data_index, char *buf){
    if(data_index < 0 || data_index >= 4063){
        return -1;
    }
    return file_system_read_block(1 + 32 + data_index, buf);
}

int file_system_write_data(unsigned int data_index, char *buf){
    if(data_index < 0 || data_index >= 4063){
        return -1;
    }
    return file_system_write_block(1 + 32 + data_index, buf);
}